/**
 * Copyright (c) 2022 Presto Labs Pte. Ltd.
 * Author: Ju
 */

#include "coin2/base/influxdb/influxdb_client.h"

#include <glog/logging.h>

#include <boost/asio/io_service.hpp>
#include <cstdint>
#include <memory>
#include <string>

#include "coin2/base/influxdb/influxdb_builder.h"
#include "coin2/base/scheduler.h"

namespace coin2::base::influxdb {

namespace {
static const std::string host = "10.81.1.203";
static const int port = 8086;
static const std::string db = "huju";
static const std::string usr = "huju";
static const std::string pwd = "123456789";
static const std::string exchange = "testbit";
static const std::string exchange_account = "test_id";
static const std::string token =
    "JOmK_SlrqhwN-PONj0z-"
    "PSp4Rv5ynFakRAChAookQu0lgt4zobPTGKFdogUiX7CE1xC01oTNrQO9Di3kKwwGPQ==";
}  // namespace

class InfluxdbTester {
 public:
  explicit InfluxdbTester(uint32_t count);
  ~InfluxdbTester() = default;

  void DoReport();
  void Run();

 private:
  void Stop();

 private:
  boost::asio::io_context ioc_;
  std::shared_ptr<Scheduler> timer_;
  InfluxdbClient client_;
  Builder builder_;
  uint64_t id_;
  uint32_t cnt_;
};

InfluxdbTester::InfluxdbTester(uint32_t count)
    : ioc_(1),
      timer_(new Scheduler(&ioc_)),
      client_(&ioc_, timer_, host, "test", port, db, token, 5, 200),
      id_(0),
      cnt_(count) {
  builder_.Measurement("order")
      .Tag("exchange", exchange)
      .Tag("exchange_account", exchange_account);
  builder_.Freeze();
}

void InfluxdbTester::Run() {
  timer_->AddPeriodicTask(std::bind(&InfluxdbTester::DoReport, this), 50,
                          "time_report");
  LOG(INFO) << "Timer Start ";
  timer_->Start();

  std::unique_ptr<boost::asio::io_context::work> writer_work;
  writer_work = std::make_unique<boost::asio::io_context::work>(ioc_);
  ioc_.run();
}

void InfluxdbTester::Stop() {
  timer_->Stop();
  ioc_.stop();
}

void InfluxdbTester::DoReport() {
  ++id_;
  builder_.TypeField("test_id", id_).TypeField("test_id_2", -id_);
  client_.SendData(builder_.Build());
  if (--cnt_ == 0) {
    Stop();
  }
}
}  // namespace coin2::base::influxdb

int main(int argc, char** argv) {
  using coin2::base::influxdb::InfluxdbTester;
  (void)argc;
  (void)argv;
  InfluxdbTester tester(100000);
  LOG(INFO) << "Run!\n";
  tester.Run();
  return 0;
}
